//
//  LHUserAccount.swift
//  sinaWeibo
//
//  Created by LiHong on 15/10/29.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit

class LHUserAccount: NSObject, NSCoding {
    
    class func userLogin() -> Bool {
        return LHUserAccount.loadAccount() != nil
    }
    /// 接收的access_token
    var access_token: String?
    
    /// access_token的生命周期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 当前授权用户的UID
    var uid: String?
    
    /// 友好显示名称
    var name: String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    /// 用户过期日期
    var expires_date: NSDate?
    
    /// KVC 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        // 将字典理的每一个key的值赋值给对应的模型属性
        setValuesForKeysWithDictionary(dict)
        
    }
    
    // 当字典里的key没有对应的值
    //MARK: - 这里写错了！ 大BUG
  //  override func setValue(value: AnyObject?, forKey key: String) {}
       // super.setValue(value, forKeyPath: key)
    
    // 当字典里的key没有对应的值
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
        return "access_token:\(access_token), expires_in:\(expires_in), uid:\(uid): expires_date:\(expires_date),\(name),\(avatar_large)"
    }
    
    // 每次调用都解档效率低，加载一次后保存到内存中
    private static var userAccount: LHUserAccount?
    
    // 文件保存路径
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/Account.plist"
    
// MARK: - 加载用户信息
    func loadUserInfo(finish: (error: NSError?) -> ()) {
        LHNetWorkTools.shareInstance.loadUserInfo { (result, error) -> () in
            if error != nil || result == nil{
                finish(error: error)
                return
            }
            
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存到沙盒中
            self.saveAccount()
            
            LHUserAccount.userAccount = self
            finish(error: nil)
        }
    }
    
// MARK: - 保存和加载用户数据
    /// 保存用户数据
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: LHUserAccount.accountPath)
        print(NSHomeDirectory())
    }
    
    /// 加载用户数据
    class func loadAccount() -> LHUserAccount? {
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? LHUserAccount
            
        }
        
        if userAccount != nil || userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
          //  print("账号有效")
            return userAccount
        }
        return nil
    }
    
    
// MARK: - 归档和解档
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}
